<template>
  <div class="w-full" :id="id">
    <tiny-grid ref="componentRef" v-bind="gridProps" v-on="events" />
  </div>
</template>

<script setup lang="ts">
import { useCreateGrid } from '@/hooks/createGrid';
import { TinyButton, TinyGridToolbar, TinyGrid } from '@opentiny/vue';
import { h, reactive, ref, useAttrs, useId, watch } from 'vue';
import Sortable from 'sortablejs';
import { useComponentExpose } from '@/hooks/useComponentExpose';
const { componentRef, exposed } = useComponentExpose<InstanceType<typeof TinyGrid>>();
const id = useId();
// const componentRef = ref<InstanceType<typeof TinyGrid>>();
const attrs = useAttrs();
const events = ref<Record<string, any>>({});

Object.keys(attrs).forEach((key) => {
  if (key.startsWith('on')) {
    events.value[key.slice(2)] = attrs[key];
  }
});

const props = defineProps({
  api: {
    type: Function,
    required: true,
  },
  params: {
    type: Object,
    default: () => ({}),
  },
  config: {
    required: true,
    type: Object as () => Partial<GridProps>,
    default: () => ({}),
  },
});
const ToolbarCom = () =>
  h(TinyGridToolbar, {
    setting: {
      storage: 'local',
      sortable: Sortable,
      // rowClassName({ row }) {
      //   return row.property === 'name' ? 'row-warning' : '';
      // },
      // onBeforeMove(type, row) {
      //   return row.property !== 'ipaddress';
      // },
      filter: '.row-warning',
    },
    refresh: true,
    fullScreen: true,
    id: 'toolbar!!-asd',
  });
const gridProps = reactive(
  useCreateGrid({
    toolbar: {
      component: ToolbarCom(),
      slots: {
        buttons(_, h) {
          return h(
            'div',
            {
              props: {
                class: '',
              },
            },
            [
              h(
                TinyButton,
                {
                  props: {
                    type: 'primary',
                  },
                },
                '新增'
              ),
              h(
                TinyButton,
                {
                  props: {
                    type: 'primary',
                  },
                },
                '删除'
              ),
            ]
          );
        },
      },
    },
    columns: [],
    data: [],
    ...props.config,
    fetchData: {
      api: getData,
    },
  })
);

watch(
  () => props.config,
  (newVal) => {
    // @ts-ignore
    gridProps = {
      ...gridProps,
      ...newVal,
    };
    console.log(gridProps);
  },
  { once: true }
);

async function getData({ page }: { page: PageConfig }) {
  return new Promise((resolve) => {
    gridProps.loading = true;

    if (props.api && typeof props.api === 'function') {
      const { currentPage, pageSize } = page;
      const params = {
        page: currentPage - 1,
        size: pageSize,
        ...props.params,
      };
      props
        .api(params, { uniqueId: id })
        .then(
          ({ data }: R) => {
            gridProps.data = data.dataList;
            return resolve({
              result: gridProps.data,
              page: { total: data.totalCount },
            });
          },
          (err: any) => {
            console.error(err);
            console.error('获取数据失败');
            gridProps.data = [];
            return resolve({
              result: gridProps.data,
              page: { total: 0 },
            });
          }
        )
        .finally(() => {
          gridProps.loading = false;
        });
    } else {
      gridProps.loading = false;
      return resolve({
        result: gridProps.data,
        page: { total: 0 },
      });
    }
  });
}

defineExpose(exposed);
</script>

<style scoped></style>
